package com.hepinghospital.user.ui.activity.nursing;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyFamilyActivity;
import com.hepinghospital.user.ui.dialog.Choose2Dialog;
import com.hepinghospital.user.ui.dialog.CustomBottomDialog;
import com.hepinghospital.user.ui.widget.ClearEditText;
import com.hepinghospital.user.util.ToastUtil;
import com.hepinghospital.user.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.AddOrderResponse;
import com.rest.response.AppointMentBean;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.NursingProjectResponse;

import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import jz.joyoung.robot.util.SoftKeyboardUtil;
import jz.joyoung.robot.util.TimeUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.ValidateUtil;

/**
 * @Description: 护理预约 填写相关信息
 * @Author: lzp
 * @CreateDate: 2022/3/9 14:47
 * @UpdateRemark: 更新说明
 */
public class AppointStep3Activity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_card_type)
    TextView tvCardtype;
    @BindView(R.id.tv_option1)
    TextView tvOption1;
    @BindView(R.id.tv_option2)
    TextView tvOption2;
    @BindView(R.id.tv_option3)
    TextView tvOption3;
    @BindView(R.id.tv_option4)
    TextView tvOption4;
    @BindView(R.id.tv_option5)
    TextView tvOption5;
    @BindView(R.id.et_position)
    ClearEditText etPosition;
    @BindView(R.id.tv_option7)
    TextView tvOption7;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_dateTime)
    TextView tvDateTime;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.ll_position)
    LinearLayout llPosition;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_option7)
    RelativeLayout rlOption7;

    static WeakReference<Activity> mActivity = null;

    private Choose2Dialog mChooseDialog;
    private CustomBottomDialog mBottomChooseDialog;
    private TimePickerView timePickerView = null;
    private MyFamilyListResponse myFamily;
    private String patientId;
    private int cardType;
    private long userId;
    private NursingProjectResponse.ChargeItemsBean chargeItemsBean;
    private String address, distance, fare, fareCoed;
    private String longitude;
    private String latitude;
    private AppointMentBean appointMentBean;

    @Override
    protected void initViews() {
        tvTitle.setText("护理预约");
    }

    @Override
    protected void initData() {
        mActivity = new WeakReference<>(this);
        chargeItemsBean = (NursingProjectResponse.ChargeItemsBean) getIntent().getSerializableExtra("item");
        address = getIntent().getStringExtra("address");
        distance = getIntent().getStringExtra("distance");
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        tvAddress.setText(address);
        getCarFee();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_nursing_appoint_step3;
    }

    @OnClick({R.id.rl_option1, R.id.rl_option2, R.id.rl_option3, R.id.rl_option4, R.id.rl_option5, R.id.rl_option7, R.id.tv_next, R.id.rl_select_patient, R.id.rl_select_time, R.id.rl_select_card})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_option1:
                showBottomChooseDialog(tvOption1, "请选择", "是", "否");
                break;
            case R.id.rl_option2:
                showBottomChooseDialog(tvOption2, "请选择", "有分泌物", "无分泌物");
                break;
            case R.id.rl_option3:
                showBottomChooseDialog(tvOption3, "请选择", "有倒睫", "无倒睫");
                break;
            case R.id.rl_option4:
                showBottomChooseDialog(tvOption4, "请选择", "通畅", "不通畅");
                break;
            case R.id.rl_option5:
                showBottomChooseDialog(tvOption5, "请选择", "有缝线", "无缝线");
                break;
            case R.id.rl_option7:
                showBottomChooseDialog(tvCardtype, "请选择", "是", "否");
                break;
            case R.id.tv_next:
                if (validate()) {
                    addNursingAppointment();
                }
                break;
            case R.id.rl_select_patient:
                startActivityForResult(MyFamilyActivity.class, 1);
                break;
            case R.id.rl_select_time:
                SoftKeyboardUtil.hideSoftKeyboard(mContext);
                showTimePickerView();
                break;
            case R.id.rl_select_card:
                showBottomChooseDialog(tvCardtype, "选择支付类型", "医保卡", "自费卡");
                break;
            default:
                break;
        }
    }

    private void addNursingAppointment() {
        appointMentBean = new AppointMentBean();
        appointMentBean.setChargeItemCode(chargeItemsBean.getChargeItemCode());
        appointMentBean.setChargeItemName(chargeItemsBean.getChargeItemName());
        appointMentBean.setChargeItemType(1);
        appointMentBean.setUnit(chargeItemsBean.getUnit());
        int price = (int) (Double.parseDouble(chargeItemsBean.getPrice()) * 100);
        appointMentBean.setPrice(price + "");
        appointMentBean.setPatientId(patientId);
        appointMentBean.setMedicalCardId(cardType);
        appointMentBean.setPhone(etPhone.getText().toString());
        appointMentBean.setAdress(address + " " + etAddressDetail.getText().toString());
//        appointMentBean.setAdress(address + " " + etAddressDetail.getText().toString());
        appointMentBean.setAppointmentTime(tvDateTime.getText().toString());
        appointMentBean.setIsEyeRed(tvOption1.getText().toString().equals("否") ? 0 : 1);
        appointMentBean.setIsSecretion(tvOption2.getText().toString().equals("无分泌物") ? 0 : 1);
        appointMentBean.setIsTrichiasis(tvOption3.getText().toString().equals("无倒睫") ? 0 : 1);
        appointMentBean.setIsUnobstructed(tvOption4.getText().toString().equals("不通畅") ? 0 : 1);
        appointMentBean.setIsSuture(tvOption5.getText().toString().equals("无缝线") ? 0 : 1);
        appointMentBean.setIsRemove(tvOption7.getText().toString().equals("否") ? 0 : 1);
        appointMentBean.setUserId(userId);
        appointMentBean.setSuturePosition(Objects.requireNonNull(etPosition.getText()).toString());
        appointMentBean.setHasFare(1);
        appointMentBean.setDistance(UtilString.saveFive(distance));
        int fareNumber = (int) (Double.parseDouble(fare) * 100);
        appointMentBean.setFare(fareNumber);
//        appointMentBean.setOrderAmount((int) (Float.parseFloat(chargeItemsBean.getPrice()) * 100));
        appointMentBean.setOrderAmount(price + fareNumber);
        appointMentBean.setFareItemCode(fareCoed);
        appointMentBean.setLatitude(latitude);
        appointMentBean.setLongitude(longitude);

        RestProxy.getInstance().addNursingAppointment(appointMentBean, new BaseObserver<AddOrderResponse>() {
                    @Override
                    public void onSuccess(AddOrderResponse result) {
                        Bundle bundle = new Bundle();
                        bundle.putString("appointmentId", result.getAppointmentId());
                        startActivity(NursingOrderDetailActivity.class, bundle);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        ToastUtil.onError(AppointStep3Activity.this, e);
                    }
                }
        );
    }

    //验证信息是否填写
    private Boolean validate() {
        if (TextUtils.isEmpty(tvPatientName.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择就诊人");
            return false;
        } else if (TextUtils.isEmpty(etPhone.getText().toString())) {
            ToastUtil.showToast(mContext, "请填写联系方式");
            return false;
        } else if (etPhone.getText().toString().trim().length() != 11 || !ValidateUtil.checkMobilePhoneNum(etPhone.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请输入正确的联系方式");
            return false;
        } else if (TextUtils.isEmpty(etAddressDetail.getText().toString())) {
            ToastUtil.showToast(mContext, "请填写详细住址");
            return false;
        } else if (TextUtils.isEmpty(tvDateTime.getText().toString()) || "点击选择时间".equals(tvDateTime.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择服务时间");
            return false;
        } else if (TextUtils.isEmpty(tvOption1.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择眼睛眼睛是否红、肿、痛");
            return false;
        } else if (TextUtils.isEmpty(tvOption2.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择有无分泌物");
            return false;
        } else if (TextUtils.isEmpty(tvOption3.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择睫毛有无倒睫");
            return false;
        } else if (TextUtils.isEmpty(tvOption4.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择泪道是否通畅");
            return false;
        } else if (TextUtils.isEmpty(tvOption5.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择眼部是否有缝线");
            return false;
        } else if (tvOption5.getText().toString().equals("有缝线") && TextUtils.isEmpty(Objects.requireNonNull(etPosition.getText()).toString())) {
            ToastUtil.showToast(mContext, "请填写缝线位置");
            return false;
        } else if (TextUtils.isEmpty(tvOption7.getText().toString())) {
            ToastUtil.showToast(mContext, "请选择是否需要拆线");
            return false;
        }
        return true;
    }

    /**
     * 服务申请信息选择框
     *
     * @param textView  textView
     * @param title     标题
     * @param leftText  选项
     * @param rightText 选项
     */
    private void showChooseDialog(TextView textView, String title, String leftText, String rightText) {
        mChooseDialog = Choose2Dialog.newInstance(textView.getText().toString());
        mChooseDialog.show(getSupportFragmentManager(), "optionDialog");
        mChooseDialog.setText(title, leftText, rightText);
        mChooseDialog.setmListener(new Choose2Dialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                textView.setText(leftText);
                if ("有缝线".equals(leftText)) {
                    tvOption7.setText("");
                    llPosition.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onCancel() {
                textView.setText(rightText);
                if ("无缝线".equals(rightText)) {
                    tvOption7.setText("否");
                    llPosition.setVisibility(View.GONE);
                }
            }
        });
    }

    private void showBottomChooseDialog(TextView textView, String title, String option1, String option2) {
        mBottomChooseDialog = CustomBottomDialog.newInstance(textView.getText().toString().trim());
        mBottomChooseDialog.show(getSupportFragmentManager(), "CustomBottomDialog");
        mBottomChooseDialog.setText(title, option1, option2);
        mBottomChooseDialog.setmListener(new CustomBottomDialog.OnItemClickListener() {
            @Override
            public void onConfirm(String option) {
                textView.setText(option);
                if ("有缝线".equals(option)) {
                    tvOption7.setText("");
                    llPosition.setVisibility(View.VISIBLE);
                    rlOption7.setVisibility(View.VISIBLE);
                } else if("无缝线".equals(option)){
                    tvOption7.setText("否");
                    llPosition.setVisibility(View.GONE);
                    rlOption7.setVisibility(View.GONE);
                }
            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 时间选择器
     */
    private void showTimePickerView() {
        if (timePickerView == null) {
            Calendar startDate = Calendar.getInstance();
            startDate.setTimeInMillis(System.currentTimeMillis());

            timePickerView = new TimePickerBuilder(this, (date, v) -> tvDateTime.setText(TimeUtil.getDatingTime(date)))
                    .setType(new boolean[]{true, true, true, true, true, false})
                    .setLineSpacingMultiplier(2.0f)
                    .setRangDate(startDate, null)
                    .setSubmitColor(ContextCompat.getColor(mContext, R.color.mainBlue))
                    .setCancelColor(ContextCompat.getColor(mContext, R.color.mainBlue))
                    .build();
        }
        timePickerView.show();
    }


    /**
     * 获取交通费
     */
    private void getCarFee() {
        RestProxy.getInstance().getNursingItemLists("3", new BaseObserver<NursingProjectResponse>() {
            @Override
            public void onSuccess(NursingProjectResponse result) {
                for (int i = 0; i < result.getChargeItems().size(); i++) {
                    if (Double.parseDouble(distance) / 1000 < Double.parseDouble(result.getChargeItems().get(i).getAdditionalInfo())) {
                        fare = result.getChargeItems().get(i).getPrice();
                        fareCoed = result.getChargeItems().get(i).getChargeItemCode();
                        break;
                    }
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        if (requestCode == 1) {
            myFamily = (MyFamilyListResponse) data.getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
            //0 未绑定 1 自费卡片 2 医保卡 3 双卡双待
            if (myFamily.cardType != 0) {
                tvCardtype.setVisibility(View.VISIBLE);
                if (myFamily.cardType == 1) {
                    cardType = 2;
                    tvCardtype.setText("自费卡");
                } else if (myFamily.cardType == 2) {
                    cardType = 1;
                    tvCardtype.setText("医保卡");
                }
            }
            tvPatientName.setText(myFamily.name);
            patientId = myFamily.patientId;
            userId = Long.parseLong(myFamily.id);
//            BaseApplication.currentFamilyId = myFamily.patientId;
        }
    }

    public static void clsoeSelf() {
        if (mActivity != null && mActivity.get() != null) {
            Activity context = mActivity.get();
            context.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mActivity != null) {
            mActivity.clear();
            mActivity = null;
        }
    }
}
